import { Col, Input, Row, Divider, Button } from "knowdesign";
import React, { useState } from "react";
import HiveIcon from "./icon/HiveIcon";
import MysqlIcon from "./icon/MysqlIcon";
import OracleIcon from "./icon/OracleIcon";
import PhoenixIcon from "./icon/PhoenixIcon";
import PostGresqlIcon from "./icon/PostgresqlIcon";
import "./index.less";

interface DataSource {
  img?: string;
  onlyDiScript: boolean;
  doc: {
    reader?: string;
    writer?: string;
  };
  disabled?: boolean;
  text: string;
  type: string;
}

interface Group {
  groupName: string;
  datasourceList: DataSource[];
}

interface SearchFilterProps {
  data: Group[];
}

const SearchFilter: React.FC<SearchFilterProps> = ({ data, selectSource }) => {
  const [query, setQuery] = useState("");
  const [selectedGroup, setSelectedGroup] = useState<string | null>(null);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setQuery(e.target.value.toLowerCase());
  };

  const [usedDataSource, setUsedDataSource] = useState([
    {
      label: "MySQL",
      value: "MySQL",
    },
    {
      label: "Hive",
      value: "HIVE",
    },
    {
      label: "Phoenix",
      value: "PHOENIX",
    },
  ]);

  const filteredData = data
    .filter(
      (group) => selectedGroup === null || group.groupName === selectedGroup
    )
    .map((group) => ({
      groupName: group.groupName,
      datasourceList: group.datasourceList.filter((ds) => {
        if (ds?.text) {
          return ds.text.toLowerCase().includes(query.toLowerCase());
        }
        return false;
      }),
    }));

  const handleGroupClick = (groupName: string) => {
    setSelectedGroup(groupName === selectedGroup ? null : groupName);
  };

  // 计算所有数据源的总数
  const totalDatasourceCount =
    data.reduce((total, group) => total + group.datasourceList.length, 0) || 0;

  const getIconComponent = (dbType: string) => {
    switch (dbType.toLowerCase()) {
      case "mysql":
        return <MysqlIcon />;
      case "postgresql":
        return <PostGresqlIcon />;
      case "oracle":
        return <OracleIcon />;
      case "sqlserver":
        return <MysqlIcon />;
      case "hive":
        return <HiveIcon />;
      case "phoenix":
        return <PhoenixIcon />;
      case "clickhouse":
        return <MysqlIcon />;
      default:
        return <MysqlIcon />;
    }
  };

  return (
    <div>
      <Row>
        <Col span={3}>
          {" "}
          <div
            style={{ display: "flex", alignItems: "center", fontSize: "14.5px", height: "30px" }}
          >
            常用数据库：
          </div>
        </Col>
        {usedDataSource.map((ds, index) => (
          <Col span={7} key={index} style={{ padding: "0px 6px" }}>
            <div
              className="lf-ds-card"
              onClick={() => selectSource(ds?.value, true)}
            >
              <div className="lf-ds-logo">{getIconComponent(ds.label)}</div>
              <div>{ds?.label}</div>
            </div>
          </Col>
        ))}
      </Row>
      <div style={{ marginBottom: 20 }}>
        <Button
          type={selectedGroup === null ? "primary" : "default"}
          style={{ marginRight: 8, marginBottom: 8, borderRadius: 4 }}
          onClick={() => handleGroupClick(null)}
        >
          全部（{totalDatasourceCount}）
        </Button>
        {data.map((group) => (
          <Button
            key={group.groupName}
            type={selectedGroup === group.groupName ? "primary" : "default"}
            style={{
              marginRight: 8,
              marginBottom: 8,
              borderRadius: 4,
              fontWeight: 600,
            }}
            onClick={() => handleGroupClick(group.groupName)}
          >
            {group.groupName}（{group.datasourceList.length}）
          </Button>
        ))}
      </div>
      <Input.Search
        // type="text"
        placeholder="请搜索数据名称"
        value={query}
        style={{ borderRadius: 4 }}
        enterButton="搜索"
        onChange={handleChange}
      />
      <Divider />
      <Row>
        {filteredData &&
          filteredData.map((group, index) =>
            group.datasourceList.map((ds) => {
              return (
                <Col span={8} key={index} style={{ padding: "0px 6px" }}>
                  <div
                    className="lf-ds-card"
                    onClick={() => selectSource(ds?.text, true)}
                  >
                    <div className="lf-ds-logo">
                      {getIconComponent(ds.text)}
                    </div>
                    <div>{ds?.text}</div>
                  </div>
                </Col>
              );
            })
          )}
      </Row>
    </div>
  );
};

export default SearchFilter;
